package com.huaao.micropolice.core.service.system.impl;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huaao.micropolice.common.util.CollectionsUtil;
import com.huaao.micropolice.core.model.content.Subject;
import com.huaao.micropolice.core.model.system.Dept;
import com.huaao.micropolice.core.model.system.Menu;
import com.huaao.micropolice.core.model.system.Menu_Subject;
import com.huaao.micropolice.core.model.system.Role;
import com.huaao.micropolice.core.repository.content.SubjectDao;
import com.huaao.micropolice.core.repository.system.DeptDao;
import com.huaao.micropolice.core.repository.system.MenuDao;
import com.huaao.micropolice.core.repository.system.MenuSubjectDao;
import com.huaao.micropolice.core.service.system.MenuSubjectService;
import com.huaao.micropolice.core.service.system.RoleService;

@Service
public class MenuSubjectServiceImpl implements MenuSubjectService{
	@Autowired
	private MenuSubjectDao menuSubjectDao;
	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private SubjectDao subjectDao;
	@Autowired
	private DeptDao deptDao;

	@Override
	public Set<String> findSubjectIds(List<Subject> subjects, String menuId, String roleId) {
		Set<String> set = new HashSet<String>();
		
		Role role = roleService.load(roleId);
		
		Set<Subject> subs = new HashSet<Subject>();
		subs.addAll(subjects);
		
		for(Menu_Subject ms : role.getMenuSubjects()){
			if(ms.getMenu().getId().equals(menuId)){
				if(subs.contains(ms.getSubject())){
					set.add(ms.getSubject().getId());
				}
			}
		}
		return set;
	}

	@Override
	@Transactional
	public void bind(String id, String menuId,String deptId, String[] ckSubs) {
		Role role = roleService.load(id);
		
		Set<Menu_Subject> filter = menuSubjectDao.filter(role, menuId, deptId);
		
		Menu menu = menuDao.load(menuId);
		role.getMenuSubjects().removeAll(filter);
		for(String subId : ckSubs){
			if(!StringUtils.isBlank(subId)){
				Subject s = subjectDao.load(subId);
				Menu_Subject ms = new Menu_Subject();
				ms.setMenu(menu);
				ms.setSubject(s);
				menuSubjectDao.save(ms);
				role.getMenuSubjects().add(ms);
			}
		}
	}

	@Override
	public Set<String> findSubjectIds(Menu menu, Role role, String deptId) {
		Dept dept = deptDao.load(deptId);
		Set<String> ids = new HashSet<String>();
		for(Menu_Subject ms : role.getMenuSubjects()){
			if(ms.getMenu().equals(menu) && ms.getSubject().getDept().equals(dept)){
				ids.add(ms.getSubject().getId());
			}
		}
		return ids;
	}
	
}
